import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
import { getToken } from '@/utils'
import router from '@/router'

let loadingInstance = null
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
})

// 添加拦截器
request.interceptors.request.use(function (config) {
  loadingInstance = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  // 获取token 添加到请求头 做接口token校验
  if (getToken()) {
    config.headers.token = getToken()
  }
  // 全局loading 显示loading 在其他地方关闭loading
  return config
}, function (error) {
  loadingInstance.close()
  return Promise.reject(error)
})
request.interceptors.response.use(function (response) {
  loadingInstance.close()
  // 判断后端返回 业务编码 code  401 403 弹出错误提示，清除登录相关缓存  跳转到登录页重新登录
  switch (response.data.code) {
    case 401:
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('role')
      ElMessage({
        type: 'error',
        message: '登录状态过期，请重新登录',
        noClose: () => {
          router.push('/login')
        }
      })
      break
    case 403:
      ElMessage({
        type: 'error',
        message: '用户未登录，请登录访问',
        noClose: () => {
          router.push('/login')
        }
      })
      break
    default:
      break
  }
  return response
}, function (error) {
  return Promise.reject(error)
})

export default request
